<?php


namespace App\Web\Controller;

use App\Web\Facades\UserAuth;
use App\Web\Model\OperatorLog;
use App\Web\Service\RightCheck;
use EchoPHP\Facades\Db;
use EchoPHP\Facades\Redis;
use EchoPHP\Http\Request;
use App\Web\Model\User as UserModel;
use App\Web\Model\Login as LoginModel;

/**
 * 用户管理模块
 * @package App\Web\Controller
 */
class User extends Controller {

    public $rightCheck = [
        'index' => RightCheck::RIGHT_ACCOUNT_USER,
        'info' => RightCheck::RIGHT_ACCOUNT_USER,
        'save' => RightCheck::RIGHT_ACCOUNT_USER,
        'lock' => RightCheck::RIGHT_ACCOUNT_USER,
        'offline' => RightCheck::RIGHT_ACCOUNT_USER,
        'resetpwd' => RightCheck::RIGHT_ACCOUNT_USER,
        'editstatus' => RightCheck::RIGHT_ACCOUNT_USER,
        'unbindphone' => RightCheck::RIGHT_ACCOUNT_USER,
    ];

    /**
     * 获取用户列表
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function index(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pageLimit/d', 10);
        $oprRole = UserAuth::getLoginInfo('issuper','');
        $teamCode = substr(UserAuth::getLoginInfo('teamcode',''),0,5);
        $search = [
            'username' => $request->getParam('username'),
            'userid' => $request->getParam('userid'),
            'cname' => $request->getParam('cname'),
            'area' => $request->getParam('area'),
            'teamcode' => $request->getParam('teamcode'),
            'withchild' => $request->getParam('withchild', 0),
            'teamrole' => $request->getParam('teamrole'),
            'status' => $request->getParam('status'),
            'islock' => $request->getParam('islock'),
            'level' => $request->getParam('level'),
            'roleid' => $request->getParam('roleid'),
        ];

        $userModel = new UserModel();
        list($pageNum, $rowFrom, $rowTo) = $userModel->paginationParameters($pageNum, $pageLimit);
        $resultBody = [];
        $count = $userModel->getListCount($search,$oprRole==1 ? null : $teamCode);
        $resultBody['totalCount'] = intval($count);
        //加入当前查询页码
        $resultBody['pagenum'] = $pageNum;
        $field = 'userid,username,cname,position,area,rolename,leader,User.status,islock,lockdate,User.issuper,downloadcount,User.roleid,User.level,User.teamcode,User.teamrole,User.teamid, Team.teamname';
        $userList = $userModel->getList($search, $rowFrom, $rowTo,$field,$oprRole==1 ? null : $teamCode,true, true);

        $resultBody['status'] = true;
        $resultBody['message'] = empty($userList) ? '未查到对应记录' : '查询成功';

        $loginModel = new LoginModel();
        $redisClient = Redis::connect('userinfo');
        for ($i = 0; $i < count($userList); $i++) {
            $userList[$i]['islogin'] = $loginModel->getLoginStatus($userList[$i]['userid']) ? 1 : 0;
            $keyName = 'userinfo:'.$userList[$i]['username'];
            $loginDate = $redisClient->hGet($keyName,'logindate');
            $userList[$i]['logindate'] = $loginDate == false ? '' : $loginDate;
        }

        $resultBody['userList'] = $userList;

        return $this->json($resultBody);
    }

    /**
     * 查询用户详细信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function info(Request $request) {
        $userId = $request->getParam('userid/d');
        $userModel = new UserModel();
        $userInfo = $userModel->getInfoInteam($userId);

        if (empty($userInfo)) {
            return $this->json(['status' => false, 'message' => '用户不存在或无权查看该用户数据']);
        }
        return $this->json(['status' => true, 'message' => '查询成功', 'userInfo' => $userInfo]);
    }

    /**
     * 用户信息保存
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function save(Request $request) {
        $userId = $request->getPost('userid/d', 0);
        $username = $request->getPost('username',0);
        $tmpArea = $request->getPost('parttimearea','');
        $cname = $request->getPost('cname');
        $roleId = $request->getPost('roleid/d');
        $teamCode = $request->getPost('teamcode');
        $teamRole = $request->getPost('teamrole');
        $level = $request->getPost('level');
        $leader = $request->getPost('leader');
        $entryDate = $request->getPost('entrydate');
        $branch = $request->getPost('branch');
        $email = $request->getPost('email');
        $mobilephone = $request->getPost('mobilephone');
        $position = $request->getPost('position');
        $department = $request->getPost('department');
        $userModel = new UserModel();
        if ($userId > 0) {
            $result = $userModel->saveUser($userId, $roleId, $teamCode, $teamRole, $level, $leader, $entryDate, $branch, $email, $mobilephone, $position, $department);
        } else {
            $result = $userModel->addUser($username, $cname, $roleId, $teamCode, $teamRole, $level, $leader, $entryDate, $branch, $email, $mobilephone, $position, $department, $tmpArea);
        }
        return $this->json($result);
    }

    /**
     * 锁定用户或者解锁(离职、在职状态变更)
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function lock(Request $request) {
        $oprId = $this->getLoginId();
        $userid = $request->getPost('userid/d');
        $lockStatus = $request->getPost('lockstatus/d', 1);
        $userModel = new UserModel();
        $result = $userModel->lock($oprId, $userid, $lockStatus);

        if ($result === false) {
            return $this->json(['status' => false, 'message' => '操作失败']);
        }
        if ($lockStatus == 0) {
            $loginModel = new LoginModel();
            $loginModel->excluded(0, $userid, '您被设为离职，无法继续操作系统');
        }
        return $this->json(['status' => true, 'message' => '操作成功']);
    }

    /**
     * 用户强制下线
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function offline(Request $request) {
        $loginId = $this->getLoginId();
        $userId = $request->getGet('userid/d');

        $loginModel = new LoginModel();
        $loginModel->excluded($loginId, $userId, '您已被系统强制下线');

        return $this->json([
            'status' => true,
            'message' => '操作成功',
        ]);
    }

    /**
     * 重置密码
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function resetpwd(Request $request) {
        $userid = $request->getPost('userid/d');
        $editorPwd = $request->getPost('password');
        $userModel = new UserModel();
        $oprId = $this->getLoginId();
        $result = $userModel->resetpwd($oprId, $editorPwd, $userid);
        return $this->json($result);
    }

    public function getTeamLeader() {
        $userModel = new UserModel();
        $result = $userModel->getTeamLeader();
        return $this->json(['status' => true, 'message' => '获取成功', 'leader' => $result['leader'], 'superadmin' => $result['superadmin']]);
    }

    public function simpleIndex(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pageLimit/d', 10);

        $search = [
            'cname' => $request->getParam('cname'),
        ];

        $userModel = new UserModel();
        list($pageNum, $rowFrom, $rowTo) = $userModel->paginationParameters($pageNum, $pageLimit);
        $resultBody = [];
        $count = $userModel->getListCount($search);
        $resultBody['totalCount'] = intval($count);
        //加入当前查询页码
        $resultBody['pagenum'] = $pageNum;
        $userList = $userModel->getList($search, $rowFrom, $rowTo, 'userid,cname,islock');

        $resultBody['status'] = true;
        $resultBody['message'] = empty($userList) ? '未查到对应记录' : '查询成功';
        $resultBody['userList'] = $userList;

        return $this->json($resultBody);
    }

    public function teamIndex(Request $request) {
        $teamCode = $request->getParam('teamcode');
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pagelimit/d', 10);

        $search = [
            'userid' => $request->getParam('userid'),
            'username' => $request->getParam('username'),
        ];

        $userModel = new UserModel();
        list($pageNum, $rowFrom, $rowTo) = $userModel->paginationParameters($pageNum, $pageLimit);
        $resultBody = [];
        $count = $userModel->getListCount($search,$teamCode);
        $resultBody['totalCount'] = intval($count);
        //加入当前查询页码
        $resultBody['pagenum'] = $pageNum;
        $userList = $userModel->getList($search, $rowFrom, $rowTo, 'userid,cname,islock,Team.teamname,User.teamcode',$teamCode,false,true);

        $resultBody['status'] = true;
        $resultBody['message'] = empty($userList) ? '未查到对应记录' : '查询成功';
        $resultBody['userList'] = $userList;

        return $this->json($resultBody);
    }

    /**
     * 用户解绑手机 需用户管理权限
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function unbindPhone(Request $request) {
        $userId = $request->getPost('userid',0);
        $oprId = UserAuth::getLoginId();
        $userModel = new UserModel();
        $result = $userModel->unbindPhone($userId,$oprId);
        if ($result['status'] == true) {
            $loginModel = new LoginModel();
            $loginModel->excluded(0,$userId,'您的账号已解除手机绑定，无法继续操作');
        }
        return $this->json($result);
    }

}
